<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Cache;
use think\Log;
use think\queue\connector\Redis;
header("Content-type: text/html; charset=utf-8");
$appid = "wx3fc5ae17b3b00f18";
$secret = "3b7351b120945dd1757ba62fdfaee68a";
class Api{
    public function index(){
        if(isset($_GET['echostr'])){
            $this->valid();//验证是否第一次
        }else{
            $this->responseMsg();//回复消息方法
        }
    }
    public function valid(){
        $echoStr = $_GET["echostr"];
        if($this->checkSignature() && $echoStr){
            echo $echoStr;
            exit;
        }
    }
    //验证服务器
    private function checkSignature(){
        //获取微信提交的参数
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = "weixin";
        //微信提交参数放入数组
        $tmpArr = array($token, $timestamp, $nonce);
        // ①将token、timestamp、nonce三个参数进行字典序排序
        sort($tmpArr, SORT_STRING);
        //②将三个参数字符串拼接成一个字符串进行sha1加密
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        //③开发者获得加密后的字符串可与signature对比
        if( $tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }


    public function responseMsg()
    {

        $postStr = file_get_contents("php://input");
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            //用户发送的消息类型判断
            switch ($RX_TYPE)
            {
                case "text":    //文本消息
                    $result = $this->receiveText($postObj);
                    break;
                case "image":   //图片消息
                    $result = $this->receiveImage($postObj);
                    break;

                case "voice":   //语音消息
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":   //视频消息
                    $result = $this->receiveVideo($postObj);
                    break;
                case "location"://位置消息
                    $result = $this->receiveLocation($postObj);
                    break;
                case "link":    //链接消息
                    $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknow msg type: ".$RX_TYPE;
                    break;
            }
            echo $result;
        }else {
            echo "";
            exit;
        }
    }

    // 接收文本消息

    private function receiveText($object)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $res =$this->getJson($url);
        $access_token = $res["access_token"];
        $openid = $object->FromUserName;
        $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid";
        $userinfo = (array)$this->getJson($get_user_info_url);
        $xx= (array)$object;
        $save['openid'] = $openid;
        $save['nickname'] =  $userinfo['nickname'];
        $save['remark'] =  $userinfo['remark'];
        $save['date'] = date('Y-m-d');
        $save['time'] = date('YmdHis');
        $save['type'] = 'text';
        $save['content'] = $xx['Content'];
        Db::name('download_info')->insert($save);
        $data = $xx['Content'];
        $content = $userinfo['nickname']."你发送的是文本，内容为：".$object->Content;
        $this->write_log($data,$openid);
        $result = $this->transmitText($object,$content);
        return $result;
    }

    //接收图片消息
    private function receiveImage($object)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $res =$this->getJson($url);
        $access_token = $res["access_token"];
        $openid = $object->FromUserName;
        $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid";
        $userinfo = (array)$this->getJson($get_user_info_url);
        $content = "你发送的是图片，地址为：".$object->PicUrl;
        $years = date('Y-m-d');
        $path = './public/weixin/'.$openid.'/'.$years.'/'.date('YmdHis').'.jpg';
        $contents = file_get_contents($object->PicUrl);
        $res = file_put_contents($path, $contents);
        if($res){
            $result = $this->transmitText($object, $content);
        }else{
            $result = $this->transmitText($object, $res);
        }

        return $result;
    }

    //接收语音消息

    private function receiveVoice($object)
    {
        $content = "你发送的是语音，媒体ID为：".$object->MediaId;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //接收视频消息
    private function receiveVideo($object)
    {
        $content = "你发送的是视频，媒体ID为：".$object->MediaId;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //接收位置消息

    private function receiveLocation($object)
    {
        $content = "你发送的是位置，纬度为：".$object->Location_X."；经度为：".$object->Location_Y."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
        $result = $this->transmitText($object, $content);
        return $result;
    }

//接收连接
    private function receiveLink($object)
    {
        $content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
        $result = $this->transmitText($object, $content);
        return $result;
    }
//回复
    private function transmitText($object, $content)
    {
        $textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }
//log
    function write_log($data,$name){
        $years = date('Y-m-d');
        //设置路径目录信息
        $url = './public/weixin/'.$name.'/'.$years.'/'.date('YmdHis').'.txt';
        $dir_name=dirname($url);
        //目录不存在就创建
        if(!file_exists($dir_name))
        {
            //iconv防止中文名乱码
            $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
        }
        $fp = fopen($url,"a");//打开文件资源通道 不存在则自动创建
        fwrite($fp,$data."\r\n");//写入文件
        fclose($fp);//关闭资源通道
    }
    //获取url返回值
    function getJson($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
}
